package com.termine.logic;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import com.termine.bean.Bean;
import com.termine.entity.Appointment;
import com.termine.entity.ClientProviderScheduleEvent;
import com.termine.entity.Location;
import com.termine.entity.ServiceSelectItem;
import com.termine.util.Logger;

@ManagedBean
@ApplicationScoped
public class AppointmentManager extends Bean {
	
	public boolean addAppointment(Location location, ServiceSelectItem service, Date start) {
		try {
			getLocationDAO().addLocation(location);
			Appointment appointment = new Appointment();
			appointment.setClient_id(getLoginJSF().getPersonalData().getClient_id());
			appointment.setService_id(service.getServiceId());
			appointment.setLocation_id(getLocationDAO().getLocationId(location));
			appointment.setStart(start);
			Calendar end = new GregorianCalendar();
			end.setTime(start);
			end.add(Calendar.MINUTE, service.getDurationInMin());
			appointment.setEnd(end.getTime());
			getAppointmentDAO().addAppointment(appointment);
			return true;
		} catch (Exception e) {
			Logger.log(e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean cancelAppointment(ClientProviderScheduleEvent event) {
		try {
			if (getLoginJSF().getWhoAmI().equals("PROVIDER")) {	// a provider can always cancel
				deleteAppointment(event);
				return true;
			}
			else {												// a client cannot cancel after the deadline
				Calendar now = new GregorianCalendar();
				Calendar deadline = new GregorianCalendar();
				deadline.add(Calendar.MINUTE, (-1) * event.getServiceCancelDeadlineInMin());
				if (deadline.after(now)) {
					return false;
				}
				else {
					deleteAppointment(event);
					return true;
				}
			}
		} catch (Exception e) {
			Logger.log(e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	private void deleteAppointment(ClientProviderScheduleEvent event) throws Exception {
		getAppointmentDAO().deleteAppointment(event.getAppointmentId());
		getLocationDAO().deleteLocation(event.getLocationId());
	}

}
